package com.zyx.zx.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyx.zx.model.domain.Team;
import com.zyx.zx.model.domain.UserTeam;
import com.zyx.zx.service.TeamService;
import com.zyx.zx.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 定时更新队伍信息
 */
@Component
@Slf4j
public class UpdateTeamJob {
    @Resource
    private TeamService teamService;
    @Resource
    private UserTeamService userTeamService;


    @Resource
    private RedissonClient redissonClient;

    /**
     * 定时更新过去的队伍信息
     */
    @Scheduled(cron = "0 */10 * * * ?")  // 2023-04-06 19:04:00  2023-04-06 19:05:00  2023-04-06 19:06:00
    public void doUpdateTeam() {
        RLock lock = redissonClient.getLock("zhixun:preUpdateTeamJob:doUpdate:lock");
        try {
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
                queryWrapper.and(qw -> qw.isNotNull("expireTime").and(teamQueryWrapper -> teamQueryWrapper.lt("expireTime", new Date())));
                List<Team> expireTimeTeams = teamService.list(queryWrapper);
                if (expireTimeTeams.isEmpty()) {
                    return;
                }
                List<Long> expireTimeTeamsId = expireTimeTeams.stream().map(team -> {
                    Long teamId = team.getId();
                    return teamId;
                }).collect(Collectors.toList());
                if (expireTimeTeamsId.isEmpty()) {
                    return;
                }
                queryWrapper.in("id", expireTimeTeamsId);
                teamService.remove(queryWrapper);
                QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
                userTeamQueryWrapper.in("teamId", expireTimeTeamsId);
                userTeamService.remove(userTeamQueryWrapper);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
